﻿using AutoMapper;
using JuCheap.Core.Data.Entity;
using JuCheap.Core.Infrastructure;
using JuCheap.Core.Infrastructure.Exceptions;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Infrastructure.Utilities;
using JuCheap.Core.IRepository;
using JuCheap.Core.IService.AppService;
using JuCheap.Core.Model;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace JuCheap.Core.Service.AppService
{
    /// <summary>
    /// 公司扩展服务
    /// </summary>
    public class CompanyService : ICompanyService
    {
        private readonly ISysCompanyRepository _companyRepository;
        private readonly ISysUserRepository _sysUserRepository;
        private readonly IUnitWork _unitWork;
        private readonly IMapper _mapper;

        /// <summary>
        /// ctor
        /// </summary>
        public CompanyService(IUnitWork unitWork, ISysCompanyRepository companyRepository, ISysUserRepository sysUserRepository, IMapper mapper)
        {
            _unitWork = unitWork;
            _companyRepository = companyRepository;
            _sysUserRepository = sysUserRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 创建公司，并初始化公司的管理员
        /// </summary>
        /// <param name="companyCreateRequest"></param>
        /// <returns></returns>
        public async Task<string> CreateAsync(CompanyCreateRequestDto companyCreateRequest)
        {
            using (await _unitWork.BeginTransactionAsync())
            {
                //创建公司信息
                var companyId = SnowFlake.NewId();
                var company = _mapper.Map<SysCompany>(companyCreateRequest);
                company.IsSystem = false;
                company.Id = company.CompanyId = companyId;
                if (await _companyRepository.ExistsAsync(x => x.CompanyName == companyCreateRequest.CompanyName))
                {
                    throw new BusinessException("公司名称重复");
                }
                await _companyRepository.InsertAsync(company);

                //初始化公司管理员用户信息
                if (await _sysUserRepository.ExistsAsync(x => x.LoginName == companyCreateRequest.AdminAccount))
                {
                    throw new BusinessException("登陆账号重复");
                }
                var adminUser = new SysUser
                {
                    CompanyId = companyId,
                    LoginName = companyCreateRequest.AdminAccount,
                    Name = "管理员",
                    SecurityKey = Guid.NewGuid().ToString("N").ToString(),
                    IsAdmin = true
                };
                adminUser.Password = companyCreateRequest.AdminPassword.ToMd5(adminUser.SecurityKey);
                await _sysUserRepository.InsertAsync(adminUser);

                await _unitWork.CommitAsync();
                return companyId;
            }
        }

        /// <summary>
        /// 更新公司信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<string> UpdateAsync(CompanyEditRequestDto req)
        {
            //创建公司信息
            var company = _mapper.Map<SysCompany>(req);
            await _companyRepository.UpdateAsync(company, x => x.CompanyName, x => x.Contact, x => x.ContactPhone, x => x.Address);
            return req.Id;
        }

        /// <summary>
        /// 公司分页扩展方法
        /// </summary>
        /// <param name="filter">基础分页参数</param>
        /// <returns></returns>
        public async Task<PagedResult<SysCompanyDto>> QueryPagesAsync(SysCompanyFilter filter)
        {
            var query = from company in _companyRepository.Queryable(false)
                        select new SysCompanyDto
                        {
                            Id = company.Id,
                            CompanyName = company.CompanyName,
                            Contact = company.Contact,
                            ContactPhone = company.ContactPhone,
                            Address = company.Address,
                            CreateTime = company.CreateTime,
                            IsSystem = company.IsSystem
                        };
            query = query.WhereIf(filter.CompanyName.IsNotBlank(), x => x.CompanyName.Contains(filter.CompanyName));

            return await query.QueryPagesAsync(filter);
        }
    }
}
